#!/usr/bin/env bash
# Test that relative paths in env directives resolve correctly from subdirectory configs
export MISE_EXPERIMENTAL=1

# Create monorepo root config
cat <<EOF >mise.toml
experimental_monorepo_root = true

[env]
ROOT_DATA = "./root-data.txt"

[tasks.root-task]
run = 'cat "\$ROOT_DATA"'
EOF

echo "root-data-content" >root-data.txt

# Create frontend project with relative path env
mkdir -p projects/frontend
cat <<'EOF' >projects/frontend/mise.toml
[env]
CONFIG_FILE = "./config.json"
DATA_DIR = "./data"
NESTED_FILE = "../../shared/shared.txt"

[tasks.build]
run = '''
echo "CONFIG_FILE=$CONFIG_FILE"
echo "DATA_DIR=$DATA_DIR"
echo "NESTED_FILE=$NESTED_FILE"
cat "$CONFIG_FILE"
cat "$NESTED_FILE"
'''
EOF

cat <<'EOF' >projects/frontend/config.json
{"name": "frontend"}
EOF
mkdir -p projects/frontend/data

# Create shared directory for nested relative path test
mkdir -p shared
echo "shared-content" >shared/shared.txt

# Create backend project with relative paths
mkdir -p projects/backend
cat <<'EOF' >projects/backend/mise.toml
[env]
ENV_FILE = "./.env"
SETTINGS_FILE = "./settings.toml"

[tasks.deploy]
run = '''
cat "$ENV_FILE"
cat "$SETTINGS_FILE"
'''
EOF

cat <<'EOF' >projects/backend/.env
DATABASE_URL=postgres://localhost/db
EOF

cat <<'EOF' >projects/backend/settings.toml
[server]
port = 8080
EOF

# Test 1: Frontend relative paths resolve from subdirectory
echo "=== Test 1: Frontend relative paths resolve correctly ==="
output=$(mise run '//projects/frontend:build')
echo "$output"
# Env vars contain relative paths as-is
echo "$output" | grep -q "CONFIG_FILE=./config.json" || (echo "FAIL: CONFIG_FILE should be relative" && exit 1)
echo "$output" | grep -q "DATA_DIR=./data" || (echo "FAIL: DATA_DIR should be relative" && exit 1)
# But the paths should resolve correctly when used (reading files works)
echo "$output" | grep -q '{"name": "frontend"}' || (echo "FAIL: Could not read config.json with relative path" && exit 1)
echo "$output" | grep -q "shared-content" || (echo "FAIL: Could not read nested relative path" && exit 1)

# Test 2: Backend relative paths work
echo "=== Test 2: Backend relative paths resolve correctly ==="
output=$(mise run '//projects/backend:deploy')
echo "$output"
echo "$output" | grep -q "DATABASE_URL=postgres://localhost/db" || (echo "FAIL: Could not read .env" && exit 1)
echo "$output" | grep -q "port = 8080" || (echo "FAIL: Could not read settings.toml" && exit 1)

# Test 3: Root task relative paths resolve from root
echo "=== Test 3: Root relative paths resolve from root ==="
output=$(mise run //:root-task)
echo "$output"
echo "$output" | grep -q "root-data-content" || (echo "FAIL: Root relative path incorrect" && exit 1)

echo "=== All relative path tests passed! ==="
